//
//  LocalAuthorizationManager.swift
//  SYGovernment
//
//  Created by 思域 on 2020/7/23.
//  Copyright © 2020 com.sy.government. All rights reserved.
//

import Foundation
import LocalAuthentication

public struct LocalAuthorizationManager {

    public static func start(_ block: @escaping ((Bool, String) -> Void)) {

        var describe: String = ""

        if (isIphoneX) {
            describe = "验证已有面容";
        } else {
            describe = "通过Home键验证已有指纹";
        }
        let context = LAContext()
        // 认证失败提示信息，为 @"" 则不提示
        //        context.localizedFallbackTitle = "输入密码";

        var error: NSError? = nil
        let result = context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error)
        if result {
            context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: describe) { (success, err) in
                if success {
                    DispatchQueue.global().async {
                        DispatchQueue.main.async {
                            block(true, "TouchID/FaceID 验证成功")
                        }
                    }
                } else if let er = err as NSError? {
                    let code = er.code
                    var text = ""
                    if code == LAError.authenticationFailed.rawValue {
                        text = "TouchID/FaceID 验证失败"
                    } else if code == LAError.userCancel.rawValue {
                        text = "TouchID/FaceID 被用户手动取消"
                    } else if code == LAError.userFallback.rawValue {
                        text = "用户不使用TouchID/FaceID,选择手动输入密码"
                    } else if code == LAError.systemCancel.rawValue {
                        text = "TouchID/FaceID 被系统取消 (如遇到来电,锁屏,按了Home键等)"
                    } else if code == LAError.passcodeNotSet.rawValue {
                        text = "TouchID/FaceID 无法启动,因为用户没有设置密码"
                    } else if code == LAError.touchIDLockout.rawValue {
                        text = "被锁定(连续多次验证TouchID/FaceID失败,系统需要用户手动输入密码)"
                    }
                    DispatchQueue.global().async {
                        DispatchQueue.main.async {
                            block(false, text)
                        }
                    }
                }
            }
        } else {
            DispatchQueue.global().async {
                DispatchQueue.main.async {
                    block(false, "当前设备不支持TouchID/FaceID")
                }
            }
        }
    }
}
